<template>
  <el-dialog
    :visible.sync="visible"
    :close-on-click-modal="false"
    :before-close="beforeClose"
    append-to-body
    top="30px"
    width="1100px"
  >
    <div v-loading="loading">
      <h5>已选项目</h5>

      <c-table
        :data="replaceViewData"
        border
        class="table-sm mb-5"
        show-summary
        :summary-method="getSummaries"
        :columns="selectColumns"
      >
        <!-- <el-table-column type="expand">
          <template slot-scope="props">
            <div class="d-flex"
                 v-for="(p,index) of columnCard"
                 :key="index">
              <div class="d-flex flex-1 align-items-center table-row">
                <div class="table-label">{{p.label}}：</div>{{props.row[p.prop] || '-'}}
              </div>
              <div class="d-flex flex-1 align-items-center table-row"
                   v-if="p.label2">
                <div class="table-label">{{p.label2}}：</div>{{props.row[p.prop2] || '-'}}
              </div>
            </div>
          </template>
        </el-table-column> -->
        <template v-slot:use="scope">
          <div class="text-truncate" :title="scope.row.funds_use_dir">
            {{ scope.row.funds_use_dir }}
          </div>
        </template>
      </c-table>

      <h5>
        替换项目
        <!-- <el-button type="primary"
                   icon="el-icon-upload2"
                   @click="showImportVisible"
                   class="ml-5">导入</el-button> -->
      </h5>
      <c-table
        :data="editData"
        border
        class="table-sm"
        show-summary
        :summary-method="getSummaries"
        :columns="editColumns"
      >
        <template v-slot:use="scope">
          <div class="text-truncate" :title="scope.row.funds_use_dir">
            {{ scope.row.funds_use_dir }}
          </div>
        </template>
      </c-table>
      <span class="text-sm">备注： 替换的项目需要与选择的项目数量一致，并保证贷款金额合计相等</span>
    </div>
    <div class="text-center mt-5" v-if="!viewMode">
      <el-button @click="onReplaceData" :loading="saveLoading" type="primary" class="btn-long">
        完成
      </el-button>
      <el-button @click="beforeClose" :loading="saveLoading" class="btn-long">取消</el-button>
    </div>
    <project-new-dialog
      :visible.sync="formVisible"
      :isBackData="true"
      :table-id="tableId"
      channel-type="1"
      :form-data="editRow"
      @back="setEditRow"
    ></project-new-dialog>

    <project-view-dialog :visible.sync="viewVisible" :query-id="queryId"></project-view-dialog>
  </el-dialog>
</template>

<script>
import ProjectNewDialog from '@/bank/views/limit/ProjectNewDialog'
import { add } from '@vimi/utils-tool'
import { mapGetters } from 'vuex'
import { dataAdapter } from '@/bank/views/limit/index'
import ProjectViewDialog from '@/bank/views/business/limit/new/ProjectViewDialog'
export default {
  components: {
    ProjectNewDialog,
    ProjectViewDialog,
  },
  props: {
    visible: Boolean,
    batchNo: String,
    batchId: String,
    formData: { type: Array, default: () => [] },
    replaceId: {
      type: String,
      default: '',
    },
  },
  data() {
    const columns = [
      { attrs: { label: '序号', type: 'index', align: 'center', minWidth: 30 } },
      { attrs: { label: '借款人/担保客户', prop: 'customer_name', minWidth: '120px' } },
      { attrs: { label: '客户类型', prop: 'org_class_name', align: 'center' } },
      { attrs: { label: '联系人', prop: 'corp_name', align: 'center' } },
      {
        attrs: { label: '所属行业', prop: 'main_business', align: 'center', minWidth: '110px' },
        slot: 'mainBudiness',
      },
      { attrs: { label: '身份证号码', prop: 'lender_idcard', minWidth: '120px' } },
      { attrs: { label: '贷款金额/拟担保金额(万元)', prop: 'warranty_amount', minWidth: '120px' } },
      {
        attrs: { label: '放款日/拟担保起始日', prop: 'load_date', align: 'center' },
        process: v => this.$utils.dateFormat(v, 'yyyy-MM-dd'),
      },
      {
        attrs: { label: '到期日', prop: 'load_end_date', align: 'center' },
        process: v => this.$utils.dateFormat(v, 'yyyy-MM-dd'),
      },
      { attrs: { label: '借款用途', prop: 'funds_use_dir', align: 'center' }, slot: 'use' },
    ]
    return {
      replaceViewData: [],
      formVisible: false,
      tableId: '',
      editRow: {},
      editData: [],
      editIndex: 0,
      selectColumns: [
        ...columns,
        {
          attrs: { label: '操作', align: 'center', width: '60px' },
          operations: [{ content: '查看', icon: 'fa fa-search', event: this.handleView }],
        },
      ],
      editColumns: [
        ...columns,
        {
          attrs: { label: '操作', align: 'center', width: '60px' },
          operations: [
            {
              content: '编辑',
              icon: 'fa fa-edit',
              event: this.handleEditRow,
              ifRender: () => !this.viewMode,
            },
            {
              content: '查看',
              icon: 'fa fa-search',
              event: this.handleView,
              ifRender: () => this.viewMode,
            },
          ],
        },
      ],
      saveLoading: false,
      loading: false,
      viewVisible: false,
      queryId: '',
    }
  },
  watch: {
    formData: {
      handler: function () {
        this.replaceViewData = [...this.formData]
        this.editData = this.formData.map(item => {
          return {
            org_class: item.org_class,
            org_class_name: item.org_class_name,
          }
        })
      },
      immediate: true,
      deep: true,
    },
    replaceId: {
      handler: function () {
        this.getReplaceData()
      },
      immediate: true,
    },
  },
  computed: {
    ...mapGetters(['org', 'user', 'clientId']),
    address() {
      return this.user.queryAddressCode
    },
    bankType() {
      return this.user.clientOrgClassType
    },
    userName() {
      return this.user.realName
    },
    bankName() {
      return this.org.orgName
    },
    viewMode() {
      return !!this.replaceId
    },
  },
  created() {},
  methods: {
    handleView(row = {}) {
      this.queryId = row.customer_related_id
      this.viewVisible = true
    },
    getReplaceData() {
      if (!this.replaceId) {
        return
      }
      this.loading = true
      this.$api
        .getData(this.$serviceName, 'replace_batch_detail_view', {
          'replace_batch_id.eq': this.replaceId,
        })
        .then(res => {
          const data = res?.data ?? []
          this.replaceViewData = data.filter(item => +item.is_replace === 1).map(dataAdapter)
          this.editData = data.filter(item => +item.is_replace === 2).map(dataAdapter)
        })
        .finally(() => {
          this.loading = false
        })
    },
    onReplaceData() {
      const replaceData = []
      const a = this.formData.reduce((p, item) => {
        replaceData.push({
          is_replace: 1,
          customer_related_id: item.customer_related_id,
          submit_client_id: this.clientId,
          submit_client_name: this.bankName,
          submit_person_name: this.userName,
        })
        return add(p, item.warranty_amount)
      }, 0)
      const b = this.editData.reduce((p, item) => {
        return add(p, item.warranty_amount)
      }, 0)
      if (a !== b) {
        return this.$message.warning('替换项目与被替换项目贷款总额需相等')
      }
      const promiseAll = []
      this.editData.forEach(item => {
        if (item.customer_name) {
          promiseAll.push(this.postData(item))
        }
      })
      const allId = []
      this.saveLoading = true
      const masterData = {
        address_code: this.address,
        apply_batch_id: this.batchId,
        bank_type: this.bankType,
        batch_no: this.batchNo,
        project_count: this.formData.length,
        project_funds: a,
        submit_client_id: this.clientId,
        submit_client_name: this.bankName,
        submit_person_name: this.userName,
        channel_type: 1,
      }
      Promise.all(promiseAll)
        .then(data => {
          data.forEach(item => {
            if (item && item.data) {
              allId.push(item.data)
            }
          })
        })
        .finally(() => {
          const slaveData = []
          allId.forEach(item => {
            slaveData.push({
              is_replace: 2,
              customer_related_id: item,
              submit_client_id: this.clientId,
              submit_client_name: this.bankName,
              submit_person_name: this.userName,
            })
          })
          if (!slaveData.length) {
            return
          }
          const formData = {
            masterTableInfo: JSON.stringify(masterData),
            masterTableName: 'replace_batch',
            slaveTableInfo: JSON.stringify([...replaceData, ...slaveData]),
            slaveTableName: 'replace_batch_detail',
          }

          // 关联添加
          this.$api
            .relatedBatch(this.$serviceName, formData)
            .then(res => {
              this.beforeClose()
              this.$message.success('提交成功！')
              this.$emit('success', res)
            })
            .catch(() => {
              this.$message.error('提交失败，请重试！')
            })
            .finally(() => {
              this.saveLoading = false
            })
        })
    },
    postData(data) {
      return this.$api.addData(this.$serviceName, 'datum_one_county_industry', data)
    },
    handleEditRow(row) {
      this.editIndex = row.index || 0
      this.editRow = row ? { ...row } : {}
      this.formVisible = true
    },
    setEditRow(data) {
      this.$set(this.editData, this.editIndex, { ...data })
    },
    beforeClose() {
      this.$emit('success', '')
      this.$emit('update:visible', false)
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (column.property === 'warranty_amount') {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += '万元'
          } else {
            sums[index] = '-'
          }
        } else {
          sums[index] = '-'
        }
      })
      return sums
    },
  },
}
</script>
<style lang="scss" scoped>
.table-label {
  padding: 2px;
  margin: 2px;
  margin-right: 15px;
  text-align: left;
  width: 200px;
}
.table-row {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgba(128, 128, 128, 0.1);
}
</style>
